import axios from "axios";
import {userNoLogin,pwdError,accountNoExit} from '@/utils/returnToast'
import router from "@/router";
import {Toast} from "vant";

//设置请求超时最大值
axios.defaults.timeout = 10000;
//设置 post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

//响应拦截
axios.interceptors.response.use(
    response=>{
        //如果请求状态码为200说明请求成功了
        if (response.data.code === 200){
            return Promise.resolve(response);
        }else {
            switch (response.data.code){
                //用户未登录状态码
                case 2001:
                    userNoLogin();
                    setTimeout(()=>{
                        router.replace({
                            path: '/login',
                            query: {
                                redirect: router.currentRoute.fullPath
                            }
                        });
                    },1000);
                    break;
                //用户密码错误
                case 2003:
                    pwdError();
                    setTimeout(()=>{
                        router.replace({
                            path: '/login',
                            query: {
                                redirect: router.currentRoute.fullPath
                            }
                        })
                    },1000);
                    break;
                //账号不存在
                case 2007:
                    accountNoExit();
                    setTimeout(()=>{
                        router.replace({
                            path: '/login',
                            query: {
                                redirect: router.currentRoute.fullPath
                            }
                        });
                    },1000);
                    break;
                default:
                    Toast({
                        message: error.response.data.message,
                        duration: 1500,
                        forbidClick: true
                    });
            }
        }
    },
)
// 请求拦截
// axios.interceptors.request.use(
//     (config) =>{
//         startLoading();
//         const token = store.state.token;
//         //设置请求头
//         config.headers.Authorization = token;
//         endLoading();
//         return config;
//     },
//     (error => {
//         Promise.reject(error);
//     })
// )

export default axios;